//
//  MineViewController.swift
//  ManBetX
//
//  Created by Cocoa on 2020/3/16.
//  Copyright © 2020 Fullen. All rights reserved.
//

/**
 * 我的 - 页面
 */
import UIKit

class MineViewController: BaseViewController,UITableViewDelegate,UITableViewDataSource {

    // MARK: -- property
    
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var tableHeaderImageView: UIImageView!
    @IBOutlet weak var headerImageButton: UIButton!// 头像Button
    @IBOutlet weak var infoView: UIView!// 存款、取款、转账、回收 -- 父视图
    @IBOutlet weak var nickNameButton: UIButton!// 昵称Button
    @IBOutlet weak var headerRightButton: UIButton!// 右侧指向Button
    lazy var dataArray: NSMutableArray = NSMutableArray.init()
    var isloading = false //加载中
    // 暂时取款功能需要
    var isEmail = String()
    var isMobie = String()
    var isRealName = String()
    var isBankcard = String()
    
    var nickName : NSString?
    
    // MARK: -- func
    
    override func viewDidLoad() {
        self.isNeedBaseConfigureFlag = false
        super.viewDidLoad()
        
        configureUI()
        configureDataSource()
        notificationCenterListener()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
       //设置导航栏背景透明
        self.navigationController?.navigationBar.setBackgroundImage(UIImage(),
                                                                   for: .default)
        self.navigationController?.navigationBar.shadowImage = UIImage()
        
        if UserHelper.getLoginStatus() {
            getUserInfo()
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
       super.viewWillDisappear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: false)
       //重置导航栏背景
       self.navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
       self.navigationController?.navigationBar.shadowImage = nil
    }
    
    // 配置所有UI
    func configureUI() {
        
        self.view.backgroundColor = UIColor.init("F8F9FB")
        self.tableView.backgroundColor = UIColor.init("F8F9FB")
        //设置tableView从顶部开始
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false;
        }
        configureInfoView()
        configureLoginOrNotUI()
    }
    // 区分已经登录和未登录的UI
    func configureLoginOrNotUI() {
        // 昵称布局、头像、我的钱包
        if UserHelper.getLoginStatus() {
            self.headerRightButton.isHidden = false
            self.nickNameButton.snp.makeConstraints { (make) in
                make.left.equalTo(self.headerImageButton.snp.right).offset(21)
                make.centerY.equalTo(self.headerImageButton).offset(-5)
            }
            let nickName: NSString = UserDefaults.standard.string(forKey: DefaultKey.USER_LOGIN_NAME)! as NSString
            self.nickNameButton.setTitle(nickName as String, for: .normal)
//            self.headerImageButton.sd_setImage(with: NSURL.init(fileURLWithPath: "") as URL, for: .normal, completed: nil)
            // 支持换头像？
            self.headerImageButton.setImage(UIImage.init(named: "login_logo"), for: .normal)
        }else {
            self.headerRightButton.isHidden = true
            self.nickNameButton.snp.makeConstraints { (make) in
                make.left.equalTo(self.headerImageButton.snp.right).offset(33)
                make.centerY.equalTo(self.headerImageButton).offset(2)
            }
            self.nickNameButton.setTitle("点击登录/注册", for: .normal)
            self.headerImageButton.setImage(UIImage.init(named: "mine_icon_defaultHead"), for: .normal)
        }
    }
    
    func configureInfoView() {
        
        let tempInfoView = MineHeaderInfoView.init(frame: CGRect.init(x: 0, y: 0, width: ScreenWidth - 20.0, height: 76.0))
        self.infoView.addSubview(tempInfoView)
        
        tempInfoView.depositClickBlock = {
            // 存款点击
            self.depositClick()
        }
        tempInfoView.withdrawalClickBlock = {
            // 取款点击
            self.withdrawalClick()
        }
        tempInfoView.transferClickBlock = {
            // 转账款点击
            self.transferClick()
        }
        tempInfoView.recycleClickBlock = {
            // 回收点击
            self.recycleClick()
        }
    }
    
    // 配置数据源
    func configureDataSource() {
        self.dataArray.removeAllObjects()
        let mineWalletVM = MineViewModel.init(entity: MineViewModel.CaseType.mineWallet)
            mineWalletVM.create()
        let mineDepositVM = MineViewModel.init(entity: MineViewModel.CaseType.mineDeposit)
            mineDepositVM.create()
        let mineWithdrawalVM = MineViewModel.init(entity: MineViewModel.CaseType.mineWithdrawal)
            mineWithdrawalVM.create()
        let mineTransferVM = MineViewModel.init(entity: MineViewModel.CaseType.mineTransfer)
            mineTransferVM.create()
        let mineSelfHelpVM = MineViewModel.init(entity: MineViewModel.CaseType.mineSelfHelp)
            mineSelfHelpVM.create()
        let mineBetVM = MineViewModel.init(entity: MineViewModel.CaseType.mineBet)
        mineBetVM.create()
        let mineShareVM = MineViewModel.init(entity: MineViewModel.CaseType.mineShare)
        mineShareVM.create()
        let mineExitVM = MineViewModel.init(entity: MineViewModel.CaseType.mineExit)
        mineExitVM.create()
        
        let firstArray = NSMutableArray.init()
        let secondArray = NSMutableArray.init()
        firstArray.add(mineWalletVM)
        firstArray.add(mineDepositVM)
        firstArray.add(mineWithdrawalVM)
        firstArray.add(mineTransferVM)
        firstArray.add(mineSelfHelpVM)
        firstArray.add(mineBetVM)
        
        secondArray.add(mineShareVM)
        
        if UserHelper.getLoginStatus() {
            // 配置我的钱包
            if let withBalance = GlobalInfo.memberInfoData!["balance"] as? String {
                if withBalance != ""{
                    let balance: Double = Double(withBalance)!
                    mineWalletVM.infoString = String(format: "%.2f", balance)
                    
                }else{
                    mineWalletVM.infoString = "0.00"
                }
            }
            // 配置安全退出
            secondArray.add(mineExitVM)
        }
        
        self.dataArray.add(firstArray)
        self.dataArray.add(secondArray)
        
        self.tableView.reloadData()
    }
    
    func getViewModel(_ indexPath: IndexPath) -> MineViewModel?{
        if indexPath.section < self.dataArray.count {
            let tempArray = self.dataArray.object(at: indexPath.section) as! NSMutableArray
            if indexPath.row < tempArray.count {
                let tempVM = tempArray.object(at: indexPath.row) as! MineViewModel
                 return tempVM
            }
        }
        return nil
    }
    
    func notificationCenterListener() {
        
        NotificationCenter.default.addObserver(self, selector: #selector(self.userLoginSucceed), name: NSNotification.Name(rawValue: DefaultKey.USER_LOGIN_SUCCEED), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(self.userLoginOut), name: NSNotification.Name(rawValue: DefaultKey.USER_LOGIN_OUT), object: nil)
    }
    
    @objc func userLoginSucceed() {
        DispatchQueue.main.async {
            self.getUserInfo()
        }
    }
    @objc func userLoginOut() {
        DispatchQueue.main.async {
            self.configureLoginOrNotUI()
            self.configureDataSource()
        }
    }
    deinit {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: DefaultKey.USER_LOGIN_SUCCEED), object: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: DefaultKey.USER_LOGIN_OUT), object: nil)
    }
    
//MARK:-- tableView
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0{
            return 0
        }
        return 12.5
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView.init()
        if section != 0{
            headerView.backgroundColor = UIColor.init("F8F9FB")
        }
        return headerView
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.0
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let tempVM = self.getViewModel(indexPath)
        return tempVM?.cellHeight() ?? 0.1
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section < self.dataArray.count {
            let tempArray = self.dataArray.object(at: section) as! NSMutableArray
            return tempArray.count
        }
        return 0
    }
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        if cell is MineTableViewCell {
            (cell as? MineTableViewCell)?.setRectCorner()
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: MineTableViewCell.getIdentifier(), for: indexPath) as! MineTableViewCell
        let tempVM = self.getViewModel(indexPath)
        
        cell.configure(tempVM as Any)
        return cell
    }
    
    // 处理header 3D变换
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offsetY:CGFloat = scrollView.contentOffset.y
        if offsetY < 0 {
            let originalHeight:CGFloat = 216 // header高度
            // 1.2 大于iOS tableView 下拉位移系数
            let scale:CGFloat = (originalHeight - offsetY*1.2) / originalHeight
            let transformScale3D:CATransform3D = CATransform3DMakeScale(scale, scale, 1.0)
            let translation3D:CATransform3D = CATransform3DMakeTranslation(0, offsetY/2, 0)
            tableHeaderImageView.layer.transform = CATransform3DConcat(transformScale3D, translation3D)
        } else {
            tableHeaderImageView.layer.transform = CATransform3DIdentity
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let tempVM = self.getViewModel(indexPath)
        switch tempVM!.caseType {
            
        case .mineWallet:// 我的钱包
            LoginViewController.loginIfNeedController(currentController: self) {
                ToolHelper.statisticsPage(pageName: "底部导航-我的-我的钱包")
                self.mainAccountPage()
            }
        case .mineDeposit:// 存款记录
            LoginViewController.loginIfNeedController(currentController: self) {
                ToolHelper.statisticsPage(pageName: "底部导航-我的-存款记录")
                self.pushTransferRecordVC(type: TransferType.deposit,path:"/walletm/dHistory")
            }
        case .mineWithdrawal:// 取款记录
            LoginViewController.loginIfNeedController(currentController: self) {
                ToolHelper.statisticsPage(pageName: "底部导航-我的-取款记录")
                self.pushTransferRecordVC(type: TransferType.withdraw,path:"/walletm/wHistory")
            }
        case .mineTransfer:// 转账记录
            LoginViewController.loginIfNeedController(currentController: self) {
                ToolHelper.statisticsPage(pageName: "底部导航-我的-转账记录")
                self.pushTransferRecordVC(type: TransferType.transfer,path:"/walletm/tHistory")
            }
        case .mineSelfHelp:// 自助记录
            LoginViewController.loginIfNeedController(currentController: self) {
                ToolHelper.statisticsPage(pageName: "底部导航-我的-自助记录")
                self.selfHelp()
            }
        case .mineBet:// 投注记录
            LoginViewController.loginIfNeedController(currentController: self) {
                ToolHelper.statisticsPage(pageName: "底部导航-我的-投注记录")
                self.pushBonusRecordVC(type: BonusType.betting,path:"/walletm/history")
            }
        case .mineShare:// 分享好友
            ToolHelper.statisticsPage(pageName: "底部导航-我的-分享好友")
            self.shareToFriends(indexPath)
        case .mineExit:// 安全退出
            ToolHelper.statisticsPage(pageName: "底部导航-我的-安全退出")
            self.logoutButtonClick()
            
        }
    }
    
// MARK: -- clickEvents
   
    func depositClick() {
        // 存款点击
        LoginViewController.loginIfNeedController(currentController: self) {
          ToolHelper.statisticsPage(pageName: "底部导航-我的-存款")
          let vc = DepoistRootVC()
          vc.isCurrentH5Page = false
          vc.hidesBottomBarWhenPushed = true
          self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    func withdrawalClick() {
        // 取款点击
        LoginViewController.loginIfNeedController(currentController: self) {
            ToolHelper.statisticsPage(pageName: "底部导航-我的-取款")
            self.withdrawalFunc()
        }
    }
    
    func transferClick() {
        // 转账点击
        LoginViewController.loginIfNeedController(currentController: self) {
            ToolHelper.statisticsPage(pageName: "底部导航-我的-转账")
            self.mainAccountPage()
        }
    }
    func recycleClick() {
        // 回收点击
        LoginViewController.loginIfNeedController(currentController: self) {
            ToolHelper.statisticsPage(pageName: "底部导航-我的-回收")
            self.oneClickRecycling()
        }
    }
    
    // 右侧按钮点击
    @IBAction func headerRightButtonClick(_ sender: UIButton) {
        LoginViewController.loginIfNeedController(currentController: self) {
            self.userInfoDetail()
        }
    }
    
    // 昵称点击
    @IBAction func nickNameButtonClick(_ sender: UIButton) {
        LoginViewController.loginIfNeedController(currentController: self) {
            ToolHelper.statisticsPage(pageName: "底部导航-我的-昵称")
            self.userInfoDetail()
        }
    }
    // 头像点击
    @IBAction func headerImageButtonClick(_ sender: UIButton) {
        LoginViewController.loginIfNeedController(currentController: self) {
            ToolHelper.statisticsPage(pageName: "底部导航-我的-头像")
            self.userInfoDetail()
        }
    }
    
    
//MARK: -- 跳转到web页面
 
    func pushNavigateWebView(toPath: String, _ title: String,sign:Bool){
       self.pushNavigateWebView(toPath: toPath, title, sign: sign, isEagleeyes: false)
    }
    
    func pushNavigateWebView(toPath: String, _ title: String,sign:Bool,isEagleeyes:Bool){
        //2018.6.4 mt 改 http 改为https
        let goNext: WebViewController = WebViewController.init()
        let url = "https://" + UserDefaults.standard.string(forKey: DefaultKey.USER_DOMAIN)! + toPath
        goNext.url = url
        goNext.title = title
        goNext.bottomOffset = 0
        goNext.signLoging=sign
        goNext.isEagleeyes = isEagleeyes
        if toPath == "/walletm/deposit" {
            goNext.isShowRefresh = false
        }
        goNext.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(goNext, animated: true)
    }
    
    // 跳转主账户
    func mainAccountPage() {
        let vc = MainAccountVC()
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    //新用户未完善资料弹窗
    func showCheckPopView(title : NSString,subTitle : NSString,isNewUser:Bool,isBingBank:Bool){
        let bgView :UIControl  = UIControl.init()
        bgView.backgroundColor = RGBAlpa(1,1,1,0.4)
        bgView.tag = 1009
        bgView.isUserInteractionEnabled = true
        bgView.addTarget(self, action: #selector(self.actionToCancelCheck), for: .touchUpInside)
        let window: UIWindow  = ((UIApplication.shared.delegate?.window)!)!
        window.addSubview(bgView)
        bgView.snp.makeConstraints { (make) in
            make.width.equalToSuperview()
            make.height.equalToSuperview()
        }
        
        let whiteView :UIView  = UIView.init(frame: UIScreen.main.bounds)
        whiteView.backgroundColor = UIColor.init(white: 1, alpha: 1)
        whiteView.layer.cornerRadius = 5;
        whiteView.layer.masksToBounds = true
        bgView.addSubview(whiteView)
        whiteView.snp.makeConstraints { (make) in
            make.width.equalTo(280)
            make.centerY.equalToSuperview()
            make.centerX.equalToSuperview()
            make.height.equalTo(220.5)
        }
        
        let  titleBtn : UIButton  = UIButton.init(type: .custom)
        titleBtn.setBackgroundImage(imageNamed("icon_common_pop_window_title_bg"), for: .normal)
        titleBtn.setTitle(title as String, for: .normal)
        titleBtn.adjustsImageWhenHighlighted = false
        titleBtn.titleEdgeInsets = UIEdgeInsets(top: -10,left: 0, bottom: 0, right: 0)
        whiteView.addSubview(titleBtn)
        titleBtn.snp.makeConstraints { (make) in
            make.width.equalToSuperview()
            make.height.equalTo(59)
            make.centerX.equalToSuperview()
            make.top.equalToSuperview()
        }
        
        let content =  UITextView.init()
        content.text = subTitle as String
        content.textColor =  HexRGBAlpha(0x333333,1)
        content.textAlignment = .center
        content.isEditable = false
        content.font = UIFont.systemFont(ofSize: 15)
        whiteView.addSubview(content)
        content.snp.makeConstraints { (make) in
            make.width.equalToSuperview().offset(-50)
            make.height.equalTo(100)
            make.centerX.equalToSuperview()
            make.top.equalTo(titleBtn.snp.bottom)
        }
        if isNewUser == true {
            let cancelBtn : UIButton  = UIButton.init(type: .custom)
            cancelBtn.setTitle("立即验证", for: .normal)
            let layerGradient = CAGradientLayer()
            layerGradient.colors = [
                UIColor.init(red: 1, green: 0.78, blue: 0.45, alpha: 1).cgColor,
                UIColor.init(red: 0.99, green: 0.57, blue: 0.33, alpha: 1).cgColor
            ]
            layerGradient.frame = CGRect(x: 0, y: 0, width: 280-60, height: 40)
            cancelBtn.layer.addSublayer(layerGradient)
            cancelBtn.layer.cornerRadius = 5;
            cancelBtn.layer.masksToBounds = true
            if isBingBank == true{ //是否只是跳转到绑定银行卡页面
                cancelBtn.addTarget(self, action: #selector(self.ationToNewUserBingBank), for: .touchUpInside)
            }else{
                cancelBtn.addTarget(self, action: #selector(self.actionToNewUserCheck), for: .touchUpInside)
            }
            
            cancelBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
            whiteView.addSubview(cancelBtn)
            cancelBtn.snp.makeConstraints { (make) in
                make.width.equalToSuperview().offset(-100)
                make.height.equalTo(40)
                make.centerX.equalToSuperview()
                make.top.equalTo(content.snp.bottom)
            }
        }else{
            
            let okBtn : UIButton  = UIButton.init(type: .custom)
            okBtn.setTitle("立即验证", for: .normal)
            let layerGradient = CAGradientLayer()
            layerGradient.colors = [
                UIColor.init(red: 1, green: 0.78, blue: 0.45, alpha: 1).cgColor,
                UIColor.init(red: 0.99, green: 0.57, blue: 0.33, alpha: 1).cgColor
            ]
            layerGradient.frame = CGRect(x: 0, y: 0, width: (280-50)/2, height: 40)
            okBtn.layer.addSublayer(layerGradient)
            okBtn.layer.cornerRadius = 5;
            okBtn.layer.masksToBounds = true
            okBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
            if isBingBank == true{ //是否只是跳转到绑定银行卡页面
                okBtn.addTarget(self, action: #selector(self.ationToNewUserBingBank), for: .touchUpInside)
            }else{
                okBtn.addTarget(self, action: #selector(self.actionToOldUserCheck), for: .touchUpInside)
            }
            
            whiteView.addSubview(okBtn)
            okBtn.snp.makeConstraints { (make) in
                make.width.equalTo((280-50)/2)
                make.height.equalTo(40)
                make.left.equalToSuperview().offset(20)
                make.top.equalTo(content.snp.bottom)
            }
            
            let cancelBtn : UIButton  = UIButton.init(type: .custom)
            cancelBtn.setTitle("下次验证", for: .normal)
            let layerGradient2 = CAGradientLayer()
            layerGradient2.colors = [
                UIColor.init(red: 0.86, green: 0.86, blue: 0.89, alpha: 1).cgColor,
                UIColor.init(red: 0.37, green: 0.37, blue: 0.37, alpha: 1).cgColor
            ]
            layerGradient2.frame = CGRect(x: 0, y: 0, width: (280-50)/2, height: 40)
            cancelBtn.layer.addSublayer(layerGradient2)
            cancelBtn.layer.cornerRadius = 5;
            cancelBtn.layer.masksToBounds = true
            cancelBtn.addTarget(self, action: #selector(self.actionToCancel2Check), for: .touchUpInside)
            cancelBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
            whiteView.addSubview(cancelBtn)
            cancelBtn.snp.makeConstraints { (make) in
                make.width.equalTo((280-50)/2)
                make.height.equalTo(40)
                make.left.equalTo(okBtn.snp.right).offset(10)
                make.top.equalTo(content.snp.bottom)
            }
        }
    }
    
    //新用户/旧用户已填信息未绑定银行卡
   @objc func ationToNewUserBingBank(){
       let window: UIWindow  = ((UIApplication.shared.delegate?.window)!)!
       window.viewWithTag(1009)?.removeFromSuperview()
       let vc = UpdateBankViewController()
       let item = UIBarButtonItem(title: "", style: .plain, target: self, action: nil)
       self.navigationItem.backBarButtonItem = item
       vc.isWithdraw = true
       vc.hidesBottomBarWhenPushed = true
       self.navigationController?.pushViewController(vc, animated: true)
   }
   
   //老用户完善手机
   @objc func actionToOldUserCheck(){
       let window: UIWindow  = ((UIApplication.shared.delegate?.window)!)!
       window.viewWithTag(1009)?.removeFromSuperview()
       DispatchQueue.main.async {
           let checkUserInfoVC = DiscountsCheckUserInfoVC(nibName:"DiscountsCheckUserInfoVC", bundle:nil)
           checkUserInfoVC.realNameIsHidden = self.isRealName as NSString
           checkUserInfoVC.phoneCheckIsHidden = self.isMobie as NSString
           checkUserInfoVC.phoneCodeIsHidden = self.isMobie as NSString
           checkUserInfoVC.emailIsHidden = self.isEmail as NSString
           checkUserInfoVC.emailCodeIsHidden = self.isEmail as NSString
           checkUserInfoVC.adressIsHidden = "yes"
           checkUserInfoVC.isWithdraw = true
           if self.isBankcard == "yes"{
               checkUserInfoVC.isBindingBank = true
           }
           checkUserInfoVC.hidesBottomBarWhenPushed = true
           self.navigationController?.pushViewController(checkUserInfoVC, animated: true)
       }
   }
   //取消验证
   @objc func actionToCancelCheck(){
       let window: UIWindow  = ((UIApplication.shared.delegate?.window)!)!
       window.viewWithTag(1009)?.removeFromSuperview()
   }
   //取消验证 进入页面
   @objc func actionToCancel2Check(){
       let window: UIWindow  = ((UIApplication.shared.delegate?.window)!)!
       window.viewWithTag(1009)?.removeFromSuperview()
       let vc = WithdrawVC()
       vc.type = 1
       vc.isNewUser = false //未验证手机则是false 验证了则是true
       vc.hidesBottomBarWhenPushed = true
       self.navigationController?.pushViewController(vc, animated: true)
   }
   //新用户完善信息
   @objc func actionToNewUserCheck(){
       let window: UIWindow  = ((UIApplication.shared.delegate?.window)!)!
       window.viewWithTag(1009)?.removeFromSuperview()
       DispatchQueue.main.async {
           let checkUserInfoVC = DiscountsCheckUserInfoVC(nibName:"DiscountsCheckUserInfoVC", bundle:nil)
           checkUserInfoVC.realNameIsHidden = self.isRealName as NSString
           checkUserInfoVC.phoneCheckIsHidden = self.isMobie as NSString
           checkUserInfoVC.phoneCodeIsHidden = self.isMobie as NSString
           checkUserInfoVC.emailIsHidden = self.isEmail as NSString
           checkUserInfoVC.emailCodeIsHidden = self.isEmail as NSString
           checkUserInfoVC.adressIsHidden = "yes"
           checkUserInfoVC.isWithdraw = true
           if self.isBankcard == "yes"{
               checkUserInfoVC.isBindingBank = true
           }
           checkUserInfoVC.hidesBottomBarWhenPushed =  true
           self.navigationController?.pushViewController(checkUserInfoVC, animated: true)
       }
   }
    
   //一键回收
   func oneClickRecycling(){
       self.showLoadHUD(title: "回收中...")
       //转入到主账户
       NetWorkRequest(API.transferAccounts(url: "1d8a7a1", gpids: ""), completion: { (responseData,statusCode,strData) -> (Void) in
           DispatchQueue.main.async {
                self.dismissLoadHUD()
               let status = responseData["status"].intValue
               if(status == 0){
                    self.getUserInfo()
                   UIHelper.alertSimpleMessage(about: "回收成功!", withDescription: "", in: self)
               }else{
                    UIHelper.alertSimpleMessage(about: "回收失败", withDescription: "", in: self)
               }
           }
       }, failed: { (faildInfo,reCode,msg) -> (Void) in
           DispatchQueue.main.async {
               self.dismissLoadHUD()
               if reCode == "21002"{
                   UIHelper.displayLoginExpireTip(self)
               }else{
                   UIHelper.alertSimpleMessage(about: "\(faildInfo)", withDescription: "", in: self)
               }
           }
       }) { () -> (Void) in
           DispatchQueue.main.async {
               self.dismissLoadHUD()
               UIHelper.alertSimpleMessage(about: "转帐未成功，请稍后重试。", withDescription: "", in: self)
               self._loadView?.removeFromSuperview()
           }
       }
   }
     //获取会员信息
    func getUserInfo() -> Void {
        self.nickName = UserDefaults.standard.string(forKey: DefaultKey.USER_LOGIN_NAME) as NSString?
        NetWorkRequest(API.memberInfoUL(url: "face82b", ccToken: API.getCcToken(), vcToken: API.getVcToken()), completion:  { (responseData,statusCode,strData) -> (Void) in
            if(statusCode == 200){
                //取出data的数据并转化为字典数据
                let dataDict = responseData["data"].dictionaryObject
                //获取到状态值
                let statusStringJson = responseData["status"]
                //把状态值的字符串转为int值
                let statusString = Int("\(statusStringJson)")
                //获取到传递过来的msg
                let msgStringJson = responseData["msg"]
                //把msgStringJson转为字符串
                let msgString = "\(msgStringJson)"
                //判断是否相等的
                if(statusString == 0){
                 let memberInfoArray = dataDict?["response"] as? [String:Any] ?? [:]
                    GlobalInfo.memberInfoData = memberInfoArray
                    DispatchQueue.main.async {
                        // 请求成功 - 需要更新本地UI
                        // 头像，昵称，我的钱包
                        self.configureLoginOrNotUI()
                        self.configureDataSource()
                    }
                }else{
                    DispatchQueue.main.async {
                        //弹出报错后的问题
                        UIHelper.alertSimpleMessage(about: msgString, withDescription: "", in: self)
                    }
                }
            }else{
                DispatchQueue.main.async {
                    //弹出报错后的问题
                    UIHelper.alertSimpleMessage(about: "获取用户信息失败!", withDescription: "", in: self)
                }
            }
        },failed: {(faildInfo,reCode,msg) -> (Void) in
            DispatchQueue.main.async {
                if reCode == "21002"{
             //       UIHelper.displayLoginExpireTip(self)
                }else{
                    UIHelper.alertSimpleMessage(about: "\(faildInfo)", withDescription: "", in: self)
                }
            }
        }
        ){() -> (Void) in
            DispatchQueue.main.async {
                UIHelper.alertSimpleMessage(about: "网络请求异常!", withDescription: "", in: self)
            }
        }
    }
    
    //存、取款、转账历史
    func  pushTransferRecordVC(type: String,path : String) -> Void {
        let vc = TransferRecordVC()
        vc.requestPath = path
        vc.requestType = type
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: true)
    }
    //我的投注
    func  pushBonusRecordVC(type: String,path : String) -> Void {
        let vc = BonusRecordVC()
        vc.requestPath = path
        vc.requestType = type
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: true)
    }
    func shareToFriends(_ indexPath: IndexPath) {
        if let message = GlobalInfo.gameInfoData?["share_msg"] as? String {
        let activityItems = [message]
        let toVC =  UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
        if kIsIpad == true{
            toVC.popoverPresentationController?.sourceView = self.tableView.cellForRow(at: indexPath)
            toVC.popoverPresentationController?.sourceRect = CGRect(x: 0, y: 0, width: kScreenW, height: toVC.popoverPresentationController?.sourceRect.height ?? 0)
        
            }
            present(toVC, animated: true, completion: nil)
        }
    }
    func selfHelp() {
        let url = "https://" + UserDefaults.standard.string(forKey: DefaultKey.USER_DOMAIN)! + "/walletm/cSHistory?isMobile=1"
        let goNext = H5WebViewController.init()
        goNext.title = "自助记录"
        goNext.url = url
        goNext.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(goNext, animated: true)
    }
    //个人详情页面数据
    func userInfoDetail() {
        showLoadHUD(title:"")
        RequestHelper.get(atPath: "/clientsAPIs/BaseInfo", withCompletion: { data in
            DispatchQueue.main.async {
                self.dismissLoadHUD()
                
              let detailVC =  TabMineDetailTableViewController.instanceFromStoryboard()!
               
               if UserHelper.getLoginStatus() == false{
                   let defaults = UserDefaults.standard
                   defaults.set(nil, forKey: DefaultKey.USER_IS_AUTO_LOGIN)
                   GlobalInfo.baseInfoData = nil
               }
               detailVC.hidesBottomBarWhenPushed = true
               self.navigationController?.pushViewController(detailVC, animated: true)
            }
        }, withError: { error in
            print(error)
            DispatchQueue.main.async {
              
                UIHelper.alertSimpleMessage(about: "", withDescription: "服务器异常,\(getErrorString())", in: self)
                self._loadView?.removeFromSuperview()
            }
        })
    }
    
    func withdrawalFunc() {
        // 取款点击
        ToolHelper.statisticsPage(pageName: "首页-首页按钮-取款")
        RequestHelper.makeCFCookie()
        if GlobalInfo.isWithdrawNative == false{
            self.pushNavigateWebView(toPath: "/walletm/withdraw", "", sign:true, isEagleeyes: true)
        }else{
            self.isloading = true
            self.showLoadHUD(title: "读取中")
            NetWorkRequest(API.getVerificationState(url: "db8695f", pagetype: "WITHDRAW_PAGE", bankcode: ""), completion: { (responseData,statusCode,strData) -> (Void) in
                let dataDict = responseData["data"].dictionary
                let pageType =  dataDict?["response"]?.string ?? ""
                //  let pageType = responseDict?["PageType"]?.string ?? ""
                let typeNeedCheck = "SHOW_VERIFICATION_PAGE"
                if pageType == typeNeedCheck{
                    NetWorkRequest(API.getVerificationAction(url: "9f42cf4", pagetype: "WITHDRAW_PAGE"), completion: { (responseData,statusCode,strData) -> (Void) in
                        let dataDict2 = responseData["data"].dictionary
                        let responseDict2 =  dataDict2?["response"]?.dictionary
                        self.isEmail = responseDict2?["has_email"]?.stringValue ?? ""
                        self.isMobie = responseDict2?["has_mobile"]?.stringValue ?? ""
                        self.isRealName = responseDict2?["has_realname"]?.stringValue ?? ""
                        self.isBankcard = responseDict2?["has_bankcard"]?.stringValue ?? ""
                        self.isloading = false
                        DispatchQueue.main.async {
                            self.dismissLoadHUD()
                            if(self.isMobie == "yes" && self.isRealName == "yes" && self.isEmail == "yes"){ //新注册已完善手机号和真实姓名和邮箱
                                if self.isBankcard == "yes"{ //新注册完善了银行卡信息
                                    let vc = WithdrawVC()
                                    vc.type = 2
                                    vc.hidesBottomBarWhenPushed = true
                                    self.navigationController?.pushViewController(vc, animated: true)
                                    
                                }else{
                                    //跳转到绑定银行卡
                                    self.showCheckPopView(title: "完善信息", subTitle: "尊敬的会员，您的个人信息尚未验证，请点击下面的按钮进行验证，谢谢！",isNewUser: true,isBingBank: true)
                                    ToolHelper.statisticsPage(pageName: "首页-取款-完善资料")
                                }
                            }else{ //新注册用户未完善资料  手机号/真实姓名/邮箱 其中n项
                                self.showCheckPopView(title: "完善信息", subTitle: "尊敬的会员，您的个人信息尚未验证，请点击下面的按钮进行验证，谢谢！",isNewUser: true,isBingBank: false)
                                ToolHelper.statisticsPage(pageName: "首页-取款-完善资料")
                            }
                        }
                    }, failed: { (faildInfo,reCode,msg) -> (Void) in
                        DispatchQueue.main.async {
                            self.dismissLoadHUD()
                            self.isloading = false
                            if reCode == "21002"{
                                UIHelper.displayLoginExpireTip(self)
                            }else{
                                UIHelper.alertSimpleMessage(about: "\(faildInfo)", withDescription: "", in: self)
                            }
                        }
                    }) { () -> (Void) in
                        DispatchQueue.main.async {
                            self.dismissLoadHUD()
                            self.isloading = false
                            UIHelper.alertSimpleMessage(about: "网络请求异常!", withDescription: "", in: self)
                        }
                    }
                }else if pageType == "SHOW_NEW_FLOW_PAGE"{ //新注册用户已完善资料
                    DispatchQueue.main.async {
                        self.dismissLoadHUD()
                        let vc = WithdrawVC()
                        vc.type = 2
                        vc.isNewUser = true
                        self.isloading = false
                        vc.hidesBottomBarWhenPushed = true
                        self.navigationController?.pushViewController(vc, animated: true)
                    }
                }else if pageType == "SHOW_OLD_FLOW_PAGE"{ //老会员
                    
                    DispatchQueue.main.async {
                        self.dismissLoadHUD()
                        self.isloading = false
                        let vc = WithdrawVC()
                        vc.type = 1
                        vc.isNewUser = false //现在统一老会员需要输入提款密码
                        vc.hidesBottomBarWhenPushed = true
                        self.navigationController?.pushViewController(vc, animated: true)
                    }
                }else{
                    self.isloading = false
                    DispatchQueue.main.async {
                        self.dismissLoadHUD()
                    }
                }
            }, failed: { (faildInfo,reCode,msg) -> (Void) in
                DispatchQueue.main.async {
                    self.dismissLoadHUD()
                    self.isloading = false
                    if reCode == "21002"{
                        UIHelper.displayLoginExpireTip(self)
                    }else{
                        UIHelper.alertSimpleMessage(about: "\(faildInfo)", withDescription: "", in: self)
                    }
                }
            }) { () -> (Void) in
                DispatchQueue.main.async {
                    self.dismissLoadHUD()
                    self.isloading = false
                    UIHelper.alertSimpleMessage(about: "网络请求异常!", withDescription: "", in: self)
                }
            }
        }
        
    }
    
    // 退出登录
    func logoutButtonClick() {
        let defaults = UserDefaults.standard
        ToolHelper.statisticsPage(pageName: "我的-个人中心-安全登出")
        defaults.set(nil, forKey: DefaultKey.USER_IS_AUTO_LOGIN)
        RequestHelper.deleteDefaultCookie()
        defaults.set(nil, forKey: DefaultKey.LOGIN_DATA)
        UserHelper.setLoginStatus(false)
        
        // 刷新页面 - 有必要时放出通知
    }
}
